import json
import base64
import logging

from dtos.simple_result import SimpleResult


class HandlerUtil(object):

    @staticmethod
    def request_body_bytes2str(request_body) -> str:
        if isinstance(request_body, bytes):
            try:
                request_body = request_body.decode("utf-8")
            except Exception as ex:
                request_body = base64.b64decode(request_body)
                logging.info(str(ex))
        if request_body:
            return request_body
        else:
            return json.dumps({})

    @staticmethod
    def set_success_response(data=None, message="success", status=200) -> dict:
        return SimpleResult(data=data, status=status, message=message).get_dic_object()

    @staticmethod
    def set_failure_response(data=None, message="failure", status=400) -> dict:
        return SimpleResult(data=data, status=status, message=message).get_dic_object()

    @staticmethod
    def set_response(data=None, message="ok", is_success=True, code=None):
        status = 200 if is_success else 400
        status = code if code else status
        return SimpleResult(data=data, status=status, message=message).get_dic_object()

